package com.sunxd.limit.core;

import com.sunxd.limit.beans.params.Context;
import com.sunxd.limit.beans.params.Limit;
import lombok.Getter;
import lombok.Setter;

import java.util.Map;
import java.util.Objects;

/**
 * @author sun.xd
 * @description: description
 * @date 2024/10/23 9:19
 */
@Setter
@Getter
public abstract class AbstractLimitHandler implements LimitHandler {

    private AbstractLimitHandler nextHandler;

    public Boolean doJudge(Context context) {
        if (canExecute(context.getLimitMap())) {
            Boolean flag = judge(context);
            if (!flag) {
                return Boolean.FALSE;
            }
        }
        if (Objects.nonNull(nextHandler)) {
            return nextHandler.doJudge(context);
        }
        return Boolean.TRUE;
    }

    public Limit getLimit(Context context) {
        return context.getLimitMap().get(key());
    }

    /**
     * 统一校验是否可处理
     *
     * @param limit limit
     * @return boolean
     */
    public boolean canExecute(Map<String, Limit> limit) {
        if (limit.containsKey(key())) {
            Limit limitCondition = limit.get(key());
            if (Objects.isNull(limitCondition.getIsOpen())) {
                return Boolean.FALSE;
            }
            return limitCondition.getIsOpen();
        }
        return Boolean.FALSE;
    }

//    private static final Map<String,AbstractLimitHandler> EXECUTE_HANDLES = Maps.newHashMap();


}
